import ArticleItem from '@/components/Articleltem';
import { useAppSelector } from '@/store';
import {
  getArticleListAction,
  updateArticleListByIdAction,
} from '@/store/action/article';
import { InfiniteScroll, PullToRefresh } from 'antd-mobile';
import { useEffect } from 'react';
import { useDispatch } from 'react-redux';

type Props = {
  channel_id: number;
};

export default function ArticleList({ channel_id }: Props) {
  const { articles } = useAppSelector((state) => state.article);
  const { channel_id: articleId } = useAppSelector((state) => state.channel);
  // 数据为空的异常情况
  // const list = articles[channel_id]?.results || [];
  // const pre_timestamp = articles[channel_id]?.pre_timestamp;
  const { results: list = [], pre_timestamp } = articles[channel_id] || {};

  // console.log(list, articles);
  const dispatch = useDispatch();
  const handleLoadMose = async () => {
    // await console.log(1);
    dispatch(
      updateArticleListByIdAction({ channel_id, timestamp: pre_timestamp })
    );
  };
  // // 2. 初始时pre_timestamp为空， 主动发一次加载请求，pre_timestamp就有值
  useEffect(() => {
    // 加上判断,避免重复请求
    if (articleId !== channel_id) return;
    // articleId 记得放进去里面,检测数据变化
    if (list.length) return;
    // 解决因为记录滚动条位置而重复发送请求

    dispatch(getArticleListAction({ channel_id }));
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [channel_id, dispatch, articleId]); //[]与[]地址不同,会造成依赖项不断变化,不断发送请求
  // 获取数据
  // 下拉刷新
  const handleRefresh = async () => {
    dispatch(getArticleListAction({ channel_id }));
  };
  return (
    <PullToRefresh onRefresh={handleRefresh}>
      {/* 如果报mapundfeiend异步数据没有回来,加个? */}
      {list?.map((item, index) => {
        // 用id不想,就用index了
        return <ArticleItem data={item} key={index} />;
      })}
      {/* 无限滚动 */}
      <InfiniteScroll
        loadMore={handleLoadMose}
        hasMore={!!pre_timestamp}
      ></InfiniteScroll>
    </PullToRefresh>
  );
}
